<template>
  <div class="container">
    <div class="app-container">
      <div class="role-btn">
        <el-button type="primary" size="mini" @click="showDialog=true">添加角色</el-button>
      </div>
      <el-table :data="roleList">
        <el-table-column prop="name" align="center" label="角色" width="200">
          <template slot-scope="scope">
            <el-input v-if="scope.row.isEdit" v-model="scope.row.editRow.name" />
            <span v-else>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="state" align="center" label="启用" width="200">
          <template slot-scope="scope">
            <el-switch v-if="scope.row.isEdit" v-model="scope.row.editRow.state" :inactive-value="0" :active-value="1" size="mini" />
            <span v-else>{{ scope.row.state === 1 ? '已启用' : scope.row.state === 0 ? '未启用' : '无' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述">
          <template slot-scope="scope">
            <el-input v-if="scope.row.isEdit" v-model="scope.row.editRow.description" type="textarea" />
            <span v-else>{{ scope.row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <template v-if="scope.row.isEdit">
              <el-button type="primary" size="mini" @click="btnEditOk(scope.row)">确认</el-button>
              <el-button size="mini" @click="scope.row.isEdit = false">取消</el-button>
            </template>
            <template v-else>
              <el-button size="mini" type="text" @click="btnPer(scope.row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEdit(scope.row)">编辑</el-button>
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="delRole(scope.row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" justify="end" align="middle" style="height:60px">
        <el-pagination
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          :total="pageParams.total"
          layout="prev, pager, next"
          @current-change="changePage"
        />
      </el-row>
    </div>
    <el-dialog :visible.sync="showDialog" title="新增角色" width="500px" @close="btnCancel">
      <el-form ref="form" label-width="120px" :model="formData" :rules="rules">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" size="small" style="width:80%" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch v-model="formData.state" :inactive-value="0" :active-value="1" size="mini" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="formData.description" type="textarea" size="small" style="width:80%" :rows="3" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="btnOk">确认</el-button>
              <el-button size="mini" @click="btnCancel">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog :visible.sync="showPerDialog" title="分配权限">
      <el-tree ref="tree" :data="permissionList" :props="{ label: 'name' }" show-checkbox node-key="id" default-expand-all :default-checked-keys="permIds" check-strictly />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button size="mini" type="primary" @click="btnPerOk">确认</el-button>
          <el-button size="mini" @click="showPerDialog=false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getroleList, addRole, updateRole, deleteRole, getRoleDetail, assignPer } from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transtoTreeData } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      roleList: [],
      pageParams: {
        page: 1,
        pagesize: 3,
        total: 0
      },
      showDialog: false,
      formData: {
        name: '',
        description: '',
        state: 0
      },
      rules: {
        name: [{
          required: true, message: '角色名称不能为空', trigger: 'blur'
        }],
        description: [{
          required: true, message: '角色描述不能为空', trigger: 'blur'
        }],
        state: []
      },
      showPerDialog: false,
      permissionList: [],
      permIds: [],
      currentId: null
    }
  },
  created() {
    this.getroleList()
  },
  methods: {
    async getroleList() {
      const { rows, total } = await getroleList(this.pageParams)
      this.roleList = rows
      this.pageParams.total = total
      this.roleList.forEach(item => {
        // 这里有个数据响应式的问题，因为新增属性，没有响应式
        // this.$set(目标对象，属性对象，初始值)
        this.$set(item, 'isEdit', false)
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    changePage(newPage) {
      this.pageParams.page = newPage
      this.getroleList()
    },
    btnOk() {
      this.$refs.form.validate(async isOk => {
        if (isOk) {
          await addRole(this.formData)
          this.$message.success('新增角色成功')
          this.getroleList()
          this.btnCancel()
        }
      })
    },
    btnCancel() {
      this.$refs.form.resetFields()
      this.showDialog = false
    },
    btnEdit(row) {
      row.isEdit = true
      // 更新缓存数据
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    async btnEditOk(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRole({ ...row.editRow, id: row.id })
        // 注意这里要用到Object.assign(目标，来源)
        // 将一个对象赋值给另一个
        Object.assign(row, {
          ...row.editRow,
          isEdit: false
        })
        this.$message.success('更新角色成功')
      } else {
        this.$message.warning('角色名称和描述不能为空')
      }
    },
    async delRole(id) {
      await deleteRole(id)
      this.$message.success('删除角色成功')
      if (this.roleList.length === 1) {
        this.pageParams.page--
      }
      this.getroleList()
    },
    async btnPer(id) {
      this.currentId = id
      const { permIds } = await getRoleDetail(id)
      this.permIds = permIds
      this.permissionList = transtoTreeData(await getPermissionList(), 0)
      this.showPerDialog = true
    },
    async btnPerOk() {
      await assignPer({
        id: this.currentId,
        permIds: this.$refs.tree.getCheckedKeys()
      })
      this.$message.success('角色分配权限成功')
      this.showPerDialog = false
    }
  }
}
</script>
<style scoped>
.role-btn{
  padding: 10px;
}
</style>
